<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    @dialog-close="dialogClose"
    :dialogWidth="dialogWidth"
    :visibleContent2="true"
    :visibleContent3="true"
    :visibleContent4="true"
    :visibleContent5="true"
  >
    <template #searchPanel>
      <CustomerSearch
        @clientForm="getfilters"
        :addCustomer="true"
        :singleChoice="false"
      />
    </template>
    <template #contentPanel>
      <el-form
        :inline="true"
        ref="filters"
        :model="filters"
        :rules="rules"
        label-width="120px"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">客户信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-form-item
            label="客户类型:"
            prop="clientType"
          >
            <el-radio-group v-model="filters.clientType">
              <el-radio-button
                v-for="item in dict['客户类型']"
                :key="item.index"
                :disabled="disabledType"
                :label="item.text"
                :value="item.value"
              >{{ item.text }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="联系人:"
            v-if="filters.clientType !== '个人客户'"
            prop="clientName"
          >
            <el-input
              clearable
              :disabled="disabledType"
              v-model.number="filters.clientName"
            />
          </el-form-item>
          <el-form-item
            label="联系电话:"
            v-if="filters.clientType !== '个人客户'"
            prop="phone"
          >
            <el-input
              clearable
              :disabled="disabledType"
              v-model.number="filters.phone"
            />
          </el-form-item>
          <el-form-item
            label="打印抬头:"
            v-if="filters.clientType !== '个人客户'"
            prop="printTitle"
          >
            <el-input
              clearable
              :disabled="disabledType"
              v-model.number="filters.printTitle"
            />
          </el-form-item>

          <el-form-item
            label="客户名称:"
            v-if="filters.clientType === '个人客户'"
            prop="clientName"
          >
            <el-input
              clearable
              :disabled="disabledType"
              v-model.number="filters.clientName"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item
            label="手机号:"
            v-if="filters.clientType === '个人客户'"
            prop="phone"
          >
            <el-input
              clearable
              :disabled="disabledType"
              v-model.number="filters.phone"
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item
            label="性别:"
            v-if="filters.clientType === '个人客户'"
            prop="genderCst"
          >
            <el-radio
              v-model="filters.genderCst"
              :disabled="disabledType"
              v-for="item in dict['性别']"
              :key="item.index"
              :label="item.text"
              :value="item.value"
            >{{ item.text }}</el-radio>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="驾驶证号:"
            prop="jszNum"
          >
            <el-input
              clearable
              :disabled="disabledType"
              v-model.number="filters.jszNum"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item
            label="驾驶证到期时间:"
            prop="jszExpireTime"
          >
            <el-date-picker
              v-model="filters.jszExpireTime"
              :disabled="disabledType"
              type="date"
              placeholder="到期时间"
              style="width: 200px"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="生日:"
            v-if="filters.clientType === '个人客户'"
            prop="birthday"
          >
            <el-date-picker
              v-model="filters.birthday"
              :disabled="disabledType"
              type="date"
              placeholder="选择生日"
              style="width: 200px"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item
            label="单位名称:"
            v-if="filters.clientType !== '个人客户'"
            prop="companyName"
          >
            <el-input
              clearable
              :disabled="disabledType"
              v-model.number="filters.companyName"
            />
          </el-form-item>
          <el-form-item
            label="地址:"
            prop="address"
          >
            <el-input
              clearable
              :disabled="disabledType"
              v-model.number="filters.address"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="会员等级:"
            prop="memberLevelDictId"
          >
            <el-select
              clearable
              ref="dragSelect"
              v-model="filters.memberLevelDictId"
              :disabled="true"
            >
              <el-option
                v-for="item in dict['客户会员等级']"
                :key="item.index"
                :value="item.value"
                :label="item.text"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="客户来源:"
            prop="clientSource"
          >
            <el-select
              clearable
              :disabled="disabledType"
              ref="dragSelect"
              v-model="filters.clientSource"
              class="drag-select"
            >
              <el-option
                v-for="item in dict['客户来源']"
                :key="item.index"
                :value="item.value"
                :label="item.text"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="所属门店:"
            v-if="filters.clientType === '个人客户'"
            prop="storeId"
          >
            <job-shop
              v-model="filters.storeId"
              :disabled="disabledType"
              placeholder="所属门店"
            />
          </el-form-item>
          <el-col :span="24">
            <el-form-item
              label="备注:"
              prop="remark"
            >
              <el-input
                type="textarea"
                clearable
                :disabled="disabledType"
                v-model.number="filters.remark"
                style="min-width: 600px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="客户喜好:"
              prop="clientLike"
            >
              <el-input
                type="textarea"
                clearable
                :disabled="disabledType"
                v-model.number="filters.clientLike"
                style="min-width: 500px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <template #contentPanel2>
      <el-row>
        <el-col :span="22">客户车辆列表</el-col>
        <el-col :span="2">
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="handleDataInsertCar('添加车辆')"
          >添加车辆</el-button>
        </el-col>
      </el-row>
      <el-divider content-position="center"></el-divider>
      <el-row>
        <data-table
          :value="carDataList"
          :total-count="carDataList.length"
          :has-action="true"
          :table-column-attributes="carTableColumnAttributes"
          :localPage="true"
        >
          <template #action="{ row, index }">
            <i
              class="el-icon-edit"
              v-if="row.add"
              title="编辑"
              style="cursor: pointer"
              @click="carLsitEdit(row, index)"
            ></i>
            <i
              class="el-icon-delete"
              title="删除"
              style="color: red; margin-left: 20px; cursor: pointer"
              @click="dataDelete(index, 1)"
            ></i>
          </template>
        </data-table>
      </el-row>
    </template>

    <template #contentPanel3>
      <el-form
        :inline="true"
        ref="subscribeSaveDomain"
        :model="subscribeSaveDomain"
        :rules="rules"
        label-width="120px"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">预约信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-form-item label="预约编号:">
            <el-input
              :disabled="true"
              v-model="subscribeSaveDomain.subscribeCode"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item
            label="预约到店日期:"
            prop="subscribeDate"
          >
            <el-date-picker
              v-model="subscribeSaveDomain.subscribeDate"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              style="width: 200px"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item
            label="预约到店时间:"
            prop="visitTime"
          >
            <el-time-picker
              style="width:200px"
              is-range
              v-model="subscribeSaveDomain.visitTime"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
              value-format="HH:mm:ss"
            >
            </el-time-picker>
          </el-form-item> -->
          <el-form-item
            label="预约开始时间:"
            prop="startVisitTime"
          >
            <el-time-select
              placeholder="起始时间"
              v-model="subscribeSaveDomain.startVisitTime"
              :picker-options="{
                start: '09:00',
                step: '00:15',
                end: '18:00',
                minTime:defalutStartVisitTime,
              }"
            >
            </el-time-select>
          </el-form-item>
          <el-form-item
            label="预约结束时间:"
            prop="endVisitTime"
          >
            <el-time-select
              placeholder="结束时间"
              v-model="subscribeSaveDomain.endVisitTime"
              :picker-options="{
                start: '09:00',
                step: '00:15',
                end: '18:00',
                  minTime: subscribeSaveDomain.startVisitTime
              }"
            >
            </el-time-select>
          </el-form-item>

          <el-form-item
            label="预约接待:"
            prop="userName"
          >
            <el-input
              v-model="subscribeSaveDomain.userName"
              style="width: 200px"
              @focus="handleDataInsert('选择接待')"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="预约来源:"
            prop="subscribeTypeDictId"
          >
            <el-select
              clearable
              ref="dragSelect"
              v-model="subscribeSaveDomain.subscribeTypeDictId"
              class="drag-select"
            >
              <el-option
                v-for="item in dict['预约来源']"
                :key="item.index"
                :value="item.value"
                :label="item.text"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="预约门店:"
            prop="storeId"
          >
            <job-shop
              v-model="subscribeSaveDomain.storeId"
              :disabled="disabledType"
              placeholder="预约门店"
            />
          </el-form-item>
          <el-form-item
            label="预约工单类型:"
            prop="subscribeWorkOrderDictId"
          >
            <el-select
              clearable
              ref="dragSelect"
              v-model="subscribeSaveDomain.subscribeWorkOrderDictId"
              class="drag-select"
            >
              <el-option
                v-for="item in dict['工单类型']"
                :key="item.index"
                :value="item.value"
                :label="item.text"
              />
            </el-select>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item
            label="预约备注:"
            prop="remark"
          >
            <el-input
              type="textarea"
              clearable
              :disabled="disabledType"
              v-model="subscribeSaveDomain.remark"
              style="min-width: 580px"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </template>

    <template #contentPanel4>
      <WorkOrderItemList
        ref="workOrderItemList"
        :addProjectButton="false"
        @setTotalAmount="setTotalAmount"
        :list="projectData"
        :showTollTypeOrworkUserId='false'
      />
    </template>

    <template #contentPanel5>
      <Fitting
        ref="fitting"
        @setTotalAmount="setTotalAmount"
        :list="carParts"
        :showTollTypeOrworkUserId='false'
      />

      <el-row>
        <el-col
          :span="24"
          align="right"
        >
          <el-button
            class="sumbitButton"
            type="primary"
            :disabled="disabledType"
            @click="saveUpdate()"
          >保存</el-button>
        </el-col>
      </el-row>
    </template>
    <template #dialog>
      <DialogDataForm
        v-if="dialogTitle == '添加车辆'"
        :value="carData"
        :type="carObjtype"
        @operate="changeListCheck"
      />
      <EmployeeTable
        v-if="dialogTitle == '选择接待'"
        @roleIdListSelectCheck="employeListSelectCheck"
        :checkList="[subscribeSaveDomain.userId]"
      />
    </template>
  </base-layout>
</template>

<script>
import baseMixin from "@/mixins/base";
import { CustomerSearch } from "@/components/index";
import Fitting from "@/views/after-sale/workOrderManage/fast/create/Fitting"; //拆分-配件列表
import WorkOrderItemList from "@/views/after-sale/workOrderManage/fast/create/WorkOrderItemList"; //拆分-项目列表
import { parseTimeToYMDHMS, getDict, conversionObjectField } from "@/utils/index";
// import { SelectProject, SelectionPackage, } from "@/components/index";
// SelectionEmployee
import DialogDataForm from "@/views/after-sale/client-manage/edit/components/DialogDataForm.vue"; //车辆信息
import {
  getSubscribeCode,
  editSubscribe,
  addSubscribe,
  editSubscribeById,
} from "@/api/after-sale/customer-center/index"; //导入预约管理接口
import EmployeeTable from "@/views/after-sale/systemManage/store/components/EmployeeTable";
import moment from 'moment';
import { getUserDiscount } from '@/utils/userDiscount';

export default {
  components: {
    Fitting,
    WorkOrderItemList,
    CustomerSearch,
    DialogDataForm,
    EmployeeTable,
  },
  mixins: [baseMixin({})],
  data () {
    return {
      pickerOptions: {
        disabledDate: (value) => {
          return !moment(value).isAfter(moment(new Date()).subtract(1, 'days'));
        }
      },
      editFiles: [],
      currentPage: 0,
      pageSize: 5,
      totalCount: 0,
      disabledType: false,
      carData: {}, //车辆编辑数据
      carObjtype: "add",
      subscribeSaveDomain: {
        carProjects: [], //项目信息
        cars: [], //车辆信息
        clientSaveDomain: {}, //客户信息
        id: "", //	integer($int32)预约id
        remark: "", //	string预约备注
        storeId: "", //	integer($int32)预约门店
        subscribeCode: "", //	string预约编号
        subscribeDate: "", //	string($date-time)预约到店开始时间 YYYY:MM:DD
        subscribeTypeDictId: "", //	integer($int32)预约来源
        subscribeWorkOrderDictId: "", //	integer($int32)预约工单类型
        userName: "", //	string预约接待
        visitTime: "", //	string预约到店结束时间  HH:MM:SS
        stationId: "", //工位id
        test: "", //工位类型
        userId: '',	//integer($int32)
        userName: '',//	string
        startVisitTime: '',//预约开始时间
        endVisitTime: '',//结束时间
      }, //预约信息
      dialogWidth: "1200px", //弹窗宽度
      carDataList: [], //车辆选择信息
      projectData: [], //项目选择信息
      carParts: [],
      parentFinttingData: [],
      carTableColumnAttributes: [
        {
          name: "车牌号",
          value: "licensePlateNumber",
          type: "text",
        },
        {
          name: "品牌",
          value: "carBrandName",
          type: "text",
        },
        {
          name: "车系",
          value: "carSeriesName",
          type: "text",
        },
        {
          name: "年款",
          value: "timeType",
          type: "text",
        },
        {
          name: "车型",
          value: "carModelName",
          type: "text",
        },
        {
          name: "车色",
          value: "carColor",
          type: "text",
        },
        {
          name: "里程数",
          value: "mileage",
          type: "text",
        },
        {
          name: "交强险公司",
          value: "companyName",
          type: "text",
        },
        {
          name: "交强险到期",
          value: "insureExpireDate",
          type: "text",
        },
        {
          name: "备注",
          value: "remark",
          type: "text",
        },
        {
          name: "录入时间",
          value: "createTime",
          type: "text",
        },
      ],
      filters: {
        address: "", //住址
        birthday: "", //出生日期
        cars: [], // 车辆信息
        clientLike: "", //客户喜好
        clientName: "", //客户名称
        clientSource: "注册客户", //客户来源
        clientType: "个人客户", //客户类型
        companyName: "", //公司名称
        jszExpireTime: "", //驾驶证到期日期
        jszNum: "", //驾驶证号
        genderCst: "男", //性别
        id: "", //客户id
        memberLevelDictId: "", //会员等级
        phone: "", //手机号
        companyTitle: "", //打印公司抬头
        remark: "", //备注
        storeId: "", //门店id
      },
      dict: {},
      rules: {
        clientName: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
        companyName: [{ required: true, message: "单位名称不能为空", trigger: "blur" }],
        phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
        memberLevelDictId: [
          { required: true, message: "会员等级不能为空", trigger: "blur" },
        ],
        clientSource: [{ required: true, message: "客户来源不能为空", trigger: "blur" }],
        storeId: [{ required: true, message: "所属门店不为空", trigger: "blur" }],
        //预约校验
        subscribeCode: [{ required: true, message: "请输入", trigger: "blur" }],
        subscribeDate: [{ required: true, message: "请选择", trigger: "blur" }],
        userName: [{ required: true, message: "请选择", trigger: "change" }],
        subscribeTypeDictId: [{ required: true, message: "请选择", trigger: "blur" }],
        storeId: [{ required: true, message: "请选择", trigger: "blur" }],
        subscribeWorkOrderDictId: [
          { required: true, message: "请选择", trigger: "blur" },
        ],
        stationId: [{ required: true, message: "请选择", trigger: "blur" }],
        startVisitTime: [{
          required: true, validator: (rule, value, callback) => {
            if (value) {
              callback();
            } else {
              callback('请输入或选择时间，若时间不可选取，则确认日期是否正确')
            }
          }
        }],
        endVisitTime: [{ required: true, message: "请选择", trigger: "change" }],
      },
      // totalAmount: 0, //折后总金额
    };
  },
  async created () {
    this.dict = getDict([
      "客户类型",
      "客户来源",
      "会员等级",
      "性别",
      "预约来源",
      "客户会员等级",
      "工位类型",
      "工单类型",
    ]);
    this.dict['客户会员等级'].map((item) => {
      if (item.text == '普卡') this.filters.memberLevelDictId = item.value
    })
  },
  watch: {
  },
  computed: {
    //计算开始时间能选的范围
    defalutStartVisitTime () {
      // this.subscribeSaveDomain.startVisitTime = '';
      let time = this.subscribeSaveDomain.subscribeDate;
      if (time && !moment(time).isAfter(moment())) {
        //如果是当天时间则，只能选时刻以后的
        return moment().format('HH:mm:ss')
      } else {
        return '08:00'
      }
    },
  },
  methods: {
    handleDataInsertCar () {
      this.carObjtype = "add";
      this.carData = {};
      this.dialogTitle = "添加车辆";
      this.dialogVisible = true;
    },
    setTotalAmount () {
      let { fitting } = this.$refs;
      // this.totalAmount = 0;
      // this.totalAmount = Number(fitting.totalAmount || 0);
      this.subscribeSaveDomain.carParts = Object.assign(
        [],
        this.$refs.fitting.finttingData
      );
    },
    //Car例表编辑事件
    carLsitEdit (value, index) {
      this.carObjtype = "edit";
      value.index = index;
      this.carData = value;
      this.dialogTitle = "添加车辆";
      this.dialogVisible = true;
    },
    //表格删除事件
    dataDelete (index, type) {
      this[`${type == 1 ? "carDataList" : "projectData"}`].splice(index, 1);
    },
    //员工选择
    employeListSelectCheck (select) {
      this.subscribeSaveDomain.userName = select[0].userName;
      this.subscribeSaveDomain.userId = select[0].id;
      this.dialogVisible = false;
    },
    //选择事件
    changeListCheck (list) {
      if (this.dialogTitle == "添加车辆") {
        list.add = true;
        if (this.carObjtype == "edit") {
          this.carDataList[list.index] = list;
        } else {
          this.carDataList.push(list);
        }
      }
      this.dialogVisible = false;
    },
    //用户搜索带回
    getfilters (value) {
      this.filters = {
        ...value,
      };
      if ("cars" in value) {
        if (Array.isArray(value.cars)) {
          value.cars.forEach((item) => {
            this.carDataList.push(item);
          });
        } else {
          this.carDataList.push(value.cars);
        }
      }
      let {
        discountInterval
      } = value; //获取折扣对象-包含用户权限折扣和会员卡折扣区间值
      //设置配件列表的折扣上下限
      let refsList = [{
        name: 'workOrderItemList',
        discountFilde: 'projectDiscount',
        coulumFilde: 'tableColumnAttributes',
      }, {
        name: 'fitting',
        discountFilde: 'partsDiscount',
        coulumFilde: 'finttingAttributes',
      }];
      refsList.map(item => {
        let dom = this.$refs[item.name];
        let list = dom[item.coulumFilde]
        list.forEach((item2) => {
          if (item2.value == "discount") {
            item2.maxFiled = discountInterval[item.discountFilde].max;
            item2.minFiled = discountInterval[item.discountFilde].min;
            item2.name = `折扣(当前客户折扣范围:${item2.minFiled}-${item2.maxFiled})`
          }
        });
      })

    },
    _getSubscribeCode () {
      getSubscribeCode().then((res) => {
        let { success, data } = res;
        if (success) {
          this.subscribeSaveDomain.subscribeCode = data;
        }
      });
    },
    //保存接口
    async saveUpdate () {
      let t = false;
      this.$refs["subscribeSaveDomain"].validate((valid) => {
        if (valid) {
          t = true;
        }
      });
      if (!t) return;
      let option = Object.assign({}, this.subscribeSaveDomain);
      option.visitTime = option.startVisitTime + '-' + option.endVisitTime;
      let _projectList = this.$refs.workOrderItemList.projectList
      option.carProjects = [];
      _projectList.map(item => {
        let obj = {
          ...item,
          carProjectId: item.carProjectId || item.id,
        };
        option.carProjects.push(obj);
      })
      let _carParts = this.$refs.fitting.finttingData
      option.carParts = [];
      _carParts.map(item => {
        let obj = {
          ...item,
          carPartsId: item.carPartsId || item.id,
        };
        option.carParts.push(obj);
      })
      option.cars = this.carDataList;
      option.clientSaveDomain = this.filters;
      //重新计算金额

      /** 保存*/
      const { success } = this.subscribeSaveDomain.id
        ? await editSubscribe(option)
        : await addSubscribe(option);
      if (success) {
        this.$message({
          message: "操作成功",
          type: "success",
        });
        this.$router.push({ path: '/customer-center/appointment' })
      } else {
        this.$message.error("操作失败");
      }
    },
  },
  mounted () {
    let { id } = this.$route.query;
    if (id) {
      editSubscribeById(id).then((res) => {
        let {
          success,
          data: { client, carProjects, carParts, car, ...data2 },
        } = res;
        if (success) {
          // this.filters = client;
          let timeArry = data2.visitTime.split("-");
          data2.visitTime = '';
          data2.startVisitTime = timeArry[0];
          data2.endVisitTime = timeArry[1];
          data2.carProjects = [];
          data2.carParts = [];
          data2.cars = [];
          data2.clientSaveDomain = {};
          this.subscribeSaveDomain = data2;
          this.carDataList.push(car);
          // this.$refs.fitting.finttingData=carParts;
          this.carParts = carParts;
          this.projectData = conversionObjectField(carProjects, 'projectType', 'projectDictValue');
          setTimeout(async () => {
            client.discountInterval = await getUserDiscount(client.id);
            this.filters = client;
            this.getfilters(this.filters)
          }, 500)
        }
      });
    } else {
      //默认接待为当前登录人
      let userInfo = JSON.parse(sessionStorage.getItem("login"));
      this.subscribeSaveDomain.userName = userInfo.userName;
      this.subscribeSaveDomain.userId = userInfo.id;
      this._getSubscribeCode(); //生成预约编号
    }
  },
};
</script>

<style lang="scss" scoped>
.el-table .delete-row {
  background: #f5f7fa;
  color: #ccc !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
}

/deep/ .el-form-item__content {
  width: 260px;
}

.el-date-editor--datetimerange.el-input,
.el-date-editor--datetimerange.el-input__inner {
  width: 210px;
}
.sumbitButton {
  margin-top: 10px;
}
</style>
